package com.xc.shopping_font.Controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xc.shopping_font.entity.Rater;
import com.xc.shopping_font.mapper.RaterMapper;
import com.xc.shopping_font.service.RaterService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hpsf.Decimal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/rate")
@Slf4j
public class RateController {

    @Resource
    private RaterService raterService;

  @Autowired
  RaterMapper raterMapper;

    @PostMapping
    public Boolean saveRate(@RequestBody Rater rater){
        return raterService.saveOrUpdate(rater);
    }


    @GetMapping("/getRate")
    public Map<String,Object> list(@RequestParam String productName){

//创建一个hashmap
        Map<String,Object> map = new HashMap<>();


        Map<String,Object> map2 = new HashMap<>();


        QueryWrapper<Rater> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("product_name",productName);

        List<Rater> raters  =  raterMapper.selectList(queryWrapper);


//if(raters == null){
//    map2.put("value",BigDecimal.ZERO);
//    map2.put("comments",BigDecimal.ZERO);
//
//    return map2;
//}



//先给她一个默认值，如果有值就给他覆盖掉



//        过滤出评分不为空的评论数据
        List<Rater>  raterList  = raters.stream().filter(rater -> rater.getValue() !=null).collect(Collectors.toList());

       Integer rateTotal =   raterList.stream().map(Rater::getValue).reduce(0,(a,b)->a+b);

       log.info(String.valueOf(rateTotal));

       Integer count = Math.toIntExact(raterList.stream().count());

       if(count != 0){
           Integer avgRate = rateTotal/count;

           //   设置商品的平均评分
           map.put("value",avgRate);
       }



//        log.info(String.valueOf(avgRate));




//  返回chilren,首先过滤出pid为空的评论数据
        List<Rater> rootComments = raters.stream().filter(rater -> rater.getPid() == null).collect(Collectors.toList());
        for (Rater rootComment : rootComments) {
           rootComment.setChildren(raters.stream().filter(rater ->  rootComment.getId()== rater.getPid()).collect(Collectors.toList()));
        }




        map.put("comments", rootComments);




       return map;




    }





}
